/**
 *   channelSelects.js 为渠道多选控件
 *   渠道控件的使用方式: 在需要加入渠道下拉列表的地方 直接写   <div  id = "channelSelectsPluginsDiv"></div>
 *   可以定义事件监听变化  function topChannelChange(obj){};
 *
 **/
var channelMap = new Map();
(function () {
    $X("/boss/channelService", "listAllTopChannel").callx({
        onResult: function (result) {
            var plug = $('div[name="channelSelectsPluginsDiv"]');
            if (plug.length === 0) {
                throw new Error('没有找到插件配置!');
            }
            var thisPlug = plug[0];
            if (thisPlug.dataset.selectedUrl) {
                var url = thisPlug.dataset.selectedUrl;
                var lastindex = url.lastIndexOf("/");

                $X(url.substring(0, lastindex), url.substring(lastindex + 1, url.length)).callx({
                    onResult: function (selected) {
                        init(result, selected);
                    },
                    onError: function (error) {

                    }
                });
            } else {
                init(result);
            }


        },
        onError: function (error) {
        }
    });

    function init(result, selected) {
        var html = '<input id="topChannelCode" name="topChannelCode" type="hidden" value=""/>'
        html += '<select style="width:100%" id="channelSelectsId" name="topChannelCode2" class="form-control" multiple >';
        /*html += '<option value="">--请选择--</option>';*/
        var option = "";
        for (var i = 0; i < result.length; i++) {
            channelMap.put(result[i].channelCode, result[i].name);
            if (selected) {
                option += '<option value=' + result[i].channelCode + ' ' + (selected.indexOf(result[i].channelCode) >= 0 ? 'selected="selected"' : '') + '>' + result[i].name + '</option>';
            } else {
                option += '<option value=' + result[i].channelCode + '>' + result[i].name + '</option>';
            }
        }
        html += option;
        html += '</select>';
        $(html).appendTo('div[name="channelSelectsPluginsDiv"]');

        $('#channelSelectsId').select2({
            closeOnSelect: false,
            selectOnBlur: true,             /*选择当前高亮*/
            allowClear: true,
            escapeMarkup: function (m) {
                return m;
            }
        });

        $('#channelSelectsId').on('change', function (e) {
            var selects = $('#channelSelectsId').select2('data');
            var selectValue = new Array();
            $.each(selects, function (index, value) {
                selectValue.push(value.id);
            });
            // console.log(selectValue.toString());
            $('#topChannelCode').val(selectValue.toString());
        });
    }
})()
